#include "Timer.h"

uint32_t Num = 0;
void Timer_Init() {
	// 配置定时器时钟使能
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
	// 外部时钟配置
	TIM_InternalClockConfig(TIM2);
	// 配置时基单元
	// 定时频率 = 72MHZ/(PSC+1)/(ARR+1) ==1s

	// 10000 /500000 = 1/50 == 0.02s == 20ms
	// 72000000 / 50000 / 7200 == 
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	// 向上计数
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInitStructure.TIM_Period = 65535-1; // ARR  自动重装
	TIM_TimeBaseInitStructure.TIM_Prescaler = 7200-1; // PSC 预分频
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructure);
	
	// 清除中断标志
	//TIM_ClearFlag(TIM2,TIM_FLAG_Update);
	// 配置中断使能    更新中断
	TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
	
	
	// 配置NVIC
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
	NVIC_Init(&NVIC_InitStructure);
	
	// 开启定时器
	TIM_Cmd(TIM2,ENABLE);
}

void TIM2_IRQHandler() {
	if(TIM_GetITStatus(TIM2,TIM_IT_Update) == SET) {
		Num++;
		TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
	}
}